//
//  SelectGoodsController.m
//  YiBaoStore
//
//  Created by 毛云河 on 2019/1/5.
//  Copyright © 2019 小河. All rights reserved.
//

#import "SelectGoodsController.h"
#import "SelectGoodsCell.h"

@interface SelectGoodsController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *myDataArray;

@property (nonatomic, copy) NSString *purchaseUrl;//跳转小程序采购链接
@property (nonatomic, copy) NSString *nextPageInfo;//翻页信息
@property (nonatomic, strong) MYHAleartView *aleartView;

@end

@implementation SelectGoodsController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNav];
    [self createTableView];
    self.myDataArray = [NSMutableArray array];
    [self httpRequestData];
}

- (void)httpRequestData
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (NOEmptyStr(self.nextPageInfo))
    {
        [dic setValue:self.nextPageInfo forKey:@"nextPageInfo"];
    }
    
    __weak SelectGoodsController *myself = self;
    [HttpRequest formPostPath:ZiCaiGoodsList_API params:dic resultBlock:^(NSDictionary *Data, MsgModel *msgModel)
     {
         NSLog(@"自采商品***%@",Data);
         if (msgModel.status == 200)
         {
             NSDictionary *attributes = Data[@"attributes"];
             self.purchaseUrl = attributes[@"purchaseUrl"];
             NSLog(@"自采商品purchaseUrl***%@",self.purchaseUrl);
             
             NSDictionary *result = Data[@"result"];
             NSArray *currentPageResult = result[@"currentPageResult"];
             
             self.nextPageInfo = result[@"nextPageInfo"];
             NSLog(@"自采商品currentPageResult***%@",currentPageResult);
             NSLog(@"自采商品nextPageInfo***%@",self.nextPageInfo);
             NSError *error;
             
             if (currentPageResult.count == 0|| [currentPageResult[0] allKeys].count == 0)
             {
                 [myself.myTableView.mj_footer endRefreshingWithNoMoreData];
             }
             else {
                 for (NSDictionary *dic in currentPageResult)
                 {
                     NSLog(@"自采商品dic--%@",dic);
                     MainModel *model = [[MainModel alloc] initWithDictionary:dic error:&error];
                     if ([model.increasePurchase isEqualToString:@"0"])
                     {
                         [myself.myDataArray addObject:model];
                     }
                 }
             }
             
             [myself.myTableView.mj_header endRefreshing];
             [myself.myTableView.mj_footer endRefreshing];
             [myself.myTableView reloadData];
         }
         else {
             [myself.myTableView.mj_header endRefreshing];
             [myself.myTableView.mj_footer endRefreshing];
         }
         
     }];
}

#pragma mark - 设置导航
- (void)setNav
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.titLabel.text = @"选择商品";
    UIView *lineView = [[UIView alloc] init];
    [self.view addSubview:lineView];
    lineView.frame = CGRectMake(0, self.bgNavView.bottom, SCREENWIDTH, 1);
    lineView.backgroundColor = RGBACOLOR(241, 241, 241, 1);
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.bgNavView addSubview:rightBtn];
    rightBtn.titleLabel.font = FontWithSize(18);
    rightBtn.frame = CGRectMake(SCREENWIDTH-72-15, self.bgNavView.bottom-20-10, 72, 18);
    [rightBtn setTitle:@"采货" forState:UIControlStateNormal];
    [rightBtn setTitleColor:RGBACOLOR(74, 144, 226, 1) forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
}

- (void)rightBtnClick:(UIButton *)sender
{
    NSLog(@"采货");
    NSString *url = [self.purchaseUrl substringFromIndex:8];
    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    launchMiniProgramReq.userName = @"gh_0307bfa8b637";  //拉起的小程序的username
    launchMiniProgramReq.path = [NSString stringWithFormat:@"%@",url];//拉起小程序页面的可带参路径，不填默认拉起小程序首页
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
    [WXApi sendReq:launchMiniProgramReq];
}

- (void)createTableView
{
    if (@available(iOS 11.0, *))
    {
        self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.bgNavView.bottom+1, SCREENWIDTH, SCREENHEIGHT-self.bgNavView.bottom-1-BottomHeight_xs) style:UITableViewStylePlain];
    }
    else {
        self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.bgNavView.bottom+1, SCREENWIDTH, SCREENHEIGHT-self.bgNavView.bottom-1-BottomHeight) style:UITableViewStylePlain];
    }
    self.myTableView.backgroundColor = RGBACOLOR(241, 241, 241, 1);
    [self.view addSubview:self.myTableView];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.sectionHeaderHeight = 0.01f;
    self.myTableView.sectionFooterHeight = 10.f;
    self.myTableView.tableHeaderView = [UIView new];
    self.myTableView.tableFooterView = [UIView new];
    
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(httpRequestNewData)];
    self.myTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(httpMoreData)];
    
    [TTKUtil setAutomaticallyAdjustsScrollViewInsetsWidth:self.myTableView withView:self];
    [self.myTableView registerClass:[SelectGoodsCell class] forCellReuseIdentifier:@"SelectGoodsCell"];
}

- (void)httpRequestNewData
{
    [self.myDataArray removeAllObjects];
    [self httpRequestData];
}

- (void)httpMoreData
{
    if (IsEmptyStr(self.nextPageInfo))
    {
        [self ShowHUDWithMessage:@"没有更多自采商品"];
        [self.myTableView.mj_footer endRefreshingWithNoMoreData];
    }else {
        [self httpRequestData];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    [self.myTableView tableViewDisplayWitMsg:@"您还没有任何活动商品，赶紧去采购吧" ifNecessaryForRowCount:self.myDataArray.count withBottonTitle:@"去采货"];
    __weak SelectGoodsController *myself = self;
    self.myTableView.myBlcok = ^(int index)
    {
        NSLog(@"去采货");
        NSString *url = [myself.purchaseUrl substringFromIndex:8];
        WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
        launchMiniProgramReq.userName = @"gh_0307bfa8b637";  //拉起的小程序的username
        launchMiniProgramReq.path = [NSString stringWithFormat:@"%@",url];//拉起小程序页面的可带参路径，不填默认拉起小程序首页
        launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
        [WXApi sendReq:launchMiniProgramReq];
    };
    return self.myDataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SelectGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelectGoodsCell"];
    cell.settingBtn.indexPath = indexPath;
    [cell.settingBtn addTarget:self action:@selector(settingBTnActivityClick:) forControlEvents:UIControlEventTouchUpInside];
    
    MainModel *model = self.myDataArray[indexPath.row];
    [cell setCellWithMode:model];
    
    return cell;
}

#pragma mark - 设置活动按钮点击事件
- (void)settingBTnActivityClick:(UIButton *)sender
{
    NSLog(@"设置活动");
    MainModel *model = self.myDataArray[sender.indexPath.row];
    self.aleartView = [[MYHAleartView alloc] initActivityWithModel:model isExChange:2];
    [self.aleartView showAlertView];
    __weak SelectGoodsController *myself = self;
    self.aleartView.ActivityGoddsBlock = ^(NSString * _Nonnull promotionPrice, NSString * _Nonnull stock)
    {
        NSLog(@"确认添加");
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:model.product_id forKey:@"itemId"];
        [dic setValue:promotionPrice forKey:@"promotionPrice"];
        [dic setValue:stock forKey:@"stock"];
        [HttpRequest formPostPath:AddActivityGoods_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
         {
             if (msgModel.status == 200)
             {
                 NSLog(@"设置活动成功");
                 [myself.aleartView removeFromSuperview];
                 [myself httpRequestNewData];
             }
         }];
        
    };
    
}



@end
